import java.io.File;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ResourceBundle;
import java.util.Vector;

import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Store;
import javax.mail.internet.MimeMessage;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

public class EmailUtils {
	public static String[] GetResult(Address to[], Address cc[]) {
		String copies[] = new String[0];
		if (cc != null) {
			if (to != null) {
				copies = new String[to.length + cc.length];

				int i;

				for (i = 0; i < to.length; i++)
					copies[i] = to[i].toString();

				for (int j = 0; j < cc.length; j++)
					copies[i++] = cc[j].toString();
			}

			else {
				copies = new String[cc.length];

				for (int i = 0; i < cc.length; i++)
					copies[i] = cc[i].toString();
			}
		}

		else if (to != null) {
			copies = new String[to.length];

			for (int i = 0; i < to.length; i++)
				copies[i] = to[i].toString();
		}
		return copies;
	}

	public static StringBuffer getContent(MainPanel mainPanel, Part current, ResourceBundle msgBundle) {
		StringBuffer content2 = new StringBuffer();
		try {

			boolean done = false;

			Multipart mp = (Multipart) current.getContent();

			BodyPart bp0 = mp.getBodyPart(0);

			content2.append(getMailContent(mainPanel, bp0, msgBundle));

			BodyPart bp = null;

			for (int i = 1; i < mp.getCount(); i++) {
				bp = mp.getBodyPart(i);

				if (bp.isMimeType("message/rfc822") || bp.isMimeType("multipart/alternative")) {
					if (bp.isMimeType("message/rfc822")) {
						content2.append("\n\n" + msgBundle.getString("MainPanel.forwardedMail") + "\n");
						content2.append(getMailContent(mainPanel, (Message) bp.getContent(), msgBundle));
					}

					if (bp.isMimeType("multipart/alternative"))
						content2.append(getMailContent(mainPanel, bp, msgBundle));
				}
			}
		} catch (UnsupportedEncodingException encodE) {
			JOptionPane.showMessageDialog(null, encodE.getMessage(), "UnsupportedEncodingException", JOptionPane.ERROR_MESSAGE);
			content2.append(msgBundle.getString("MainPanel.unreadableMsgLabel"));
		}

		catch (Exception e) {
			e.printStackTrace();
		}
		return content2;

	}

	/**
	 * Recursive function to get a mail part's content
	 * @param mainPanel 
	 * 
	 * @param current
	 *            part to be examined
	 * @return content of this part
	 */
	public final static StringBuffer getMailContent(MainPanel mainPanel, Part current, ResourceBundle msgBundle) {
		
		mainPanel.checkConnect();
		StringBuffer content2 = new StringBuffer();

		try {
			if (current.isMimeType("text/plain"))
				content2.append((String) current.getContent());

			else if (current.isMimeType("text/html")) {
				mainPanel.getAttachment().setVisible(true);
				content2.append(msgBundle.getString("MainPanel.htmlMsgLabel"));
			}

			else if (current.isMimeType("multipart/alternative")) {
				mainPanel.getAttachment().setVisible(true);

				Multipart mp = (Multipart) current.getContent();
				BodyPart bp = null;

				for (int i = 0; i < mp.getCount(); i++) {
					bp = mp.getBodyPart(i);

					if (bp.isMimeType("text/plain")) {
						content2.append((String) bp.getContent());
						break;
					}
				}
			}

			else if (current.isMimeType("multipart/mixed") || current.isMimeType("multipart/related") || current.isMimeType("multipart/signed")) {
				content2 = getContent(mainPanel, current, msgBundle);
			}

			else if (current.isMimeType("message/rfc822")) {
				content2.append("\n\n" + msgBundle.getString("MainPanel.forwardedMail") + "\n");
				content2.append(getMailContent(mainPanel, (Message) current.getContent(), msgBundle));
			}

			else if (current.isMimeType("multipart/report")) {
				content2 = getContent(mainPanel, current, msgBundle);
			}

			else
				content2.append(msgBundle.getString("MainPanel.unreadableMsgLabel"));
		}

		catch (UnsupportedEncodingException encodE) {
			JOptionPane.showMessageDialog(null, encodE.getMessage(), "UnsupportedEncodingException", JOptionPane.ERROR_MESSAGE);
			content2.append(msgBundle.getString("MainPanel.unreadableMsgLabel"));
		}

		catch (Exception e) {
			e.printStackTrace();
		}

		return (content2);
	}
	
	/**
	 * Tries to apply every filter to the mail
	 * 
	 * @param m
	 *            message to be tested
	 * @return boolean telling wether changes have been made or not
	 */
	public static boolean applyFilters(Message m, Profile profile, Folder currentFolder, Store store) {
		try {
			Vector filters = profile.getFilters();

			int size = filters.size();

			Filter f;
			String origFolder = m.getFolder().toString();
			boolean ok;
			String condition;
			Address[] a;
			String currentSubject = m.getSubject();
			String trigger;

			for (int i = 0; i < size; i++) {
				f = (Filter) filters.get(i);

				ok = false;

				condition = f.getCondition();

				if (condition.compareTo("From") == 0) {
					a = m.getFrom();

					if (a[0].toString().indexOf(f.getTrigger()) != -1)
						ok = true;
				}

				else if ((condition.compareTo("Subject") == 0) && (currentSubject != null) && (currentSubject.indexOf(f.getTrigger()) != -1))
					ok = true;

				else if (condition.compareTo("Dest") == 0) {
					trigger = f.getTrigger();

					a = m.getRecipients(Message.RecipientType.TO);

					// can be null if some cases (usually mail sent
					// automatically)...
					if (a != null) {
						for (int j = 0; j < a.length; j++) {
							if (a[j].toString().indexOf(trigger) != -1) {
								ok = true;
								break;
							}
						}
					}

					if (!ok) {
						a = m.getRecipients(Message.RecipientType.CC);

						if (a != null) {
							for (int j = 0; j < a.length; j++) {
								if (a[j].toString().indexOf(trigger) != -1) {
									ok = true;
									break;
								}
							}
						}

						if (!ok) {
							a = m.getRecipients(Message.RecipientType.BCC);

							if (a != null) {
								for (int j = 0; j < a.length; j++) {
									if (a[j].toString().indexOf(trigger) != -1) {
										ok = true;
										break;
									}
								}
							}
						}
					}
				}

				if (ok) {
					String action = f.getAction();

					if (action.compareTo("Copy") == 0) {
						MailClient.copyMsg(store, currentFolder, ((MimeMessage) m).getMessageID(), f.getTarget());

						return (true);
					}

					else if (action.compareTo("Move") == 0) {
						MailClient.moveMsg(store, currentFolder, ((MimeMessage) m).getMessageID(), f.getTarget());

						return (true);
					}

					else if (action.compareTo("Delete") == 0) {
						MailClient.deleteMessage(store, currentFolder, ((MimeMessage) m).getMessageID());

						return (true);
					}
				}
			}
		}

		catch (Exception ex) {
			ex.printStackTrace();
		}

		return (false);
	}
	
	/** Saves the current mail in a text file */
	public static final void saveMessage(Message message, ResourceBundle msgBundle) {
		JFileChooser fc = new JFileChooser();

		int val = fc.showSaveDialog(null);

		if (val == JFileChooser.APPROVE_OPTION) {
			File file = fc.getSelectedFile();

			if (file != null) {
				try {
					int choice;

					while (file.exists()) {
						choice = JOptionPane.showConfirmDialog(null, msgBundle.getString("MainPanel.fileExistsLabel"), "MainPanel", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);

						if (choice == JOptionPane.YES_OPTION)
							break;

						val = fc.showSaveDialog(null);

						if (val == JFileChooser.APPROVE_OPTION)
							file = fc.getSelectedFile();

						else
							return;
					}

					FileOutputStream out = new FileOutputStream(file);
					message.writeTo(out);
					out.close();
				}

				catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		}
	}
}
